﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.IO;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Undertaking_Form : LayoutsPageBase
    {

        #region Variables
        public static string SiteURL;
        public static string MainLstName { get; set; }
        public static string MainListName { get; set; }
        public static string SourceLstName { get; set; }
        public static string DocumentTypesList;

        private string fileName = "";
        protected static string refNo { set; get; }
        private double length;
        byte[] contents;
        private static int ItemId { set; get; }
        private string Message = null;
        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        private string ErrorMsgs;

        DataTable dt = null;//datatable use for multiple file upload
        DataRow dr;//datarow use for multiple file upload
        DataColumn dc;//datacolumn use for multiple file upload
        double count = 0;//count of file size


        SPHelper obj = new SPHelper();

        #endregion

        public Undertaking_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Undertaking Attachments";
            MainListName = "Undertaking Forms";
            SourceLstName = "Leave Request Forms";
            DocumentTypesList = "DocumentTypes";
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            lblMessage.Text = "";
            lblRecords.Text = "";
            if (!IsPostBack)
            {
                dtDate.SelectedDate = DateTime.Today.Date;
                if (!string.IsNullOrEmpty(Request.QueryString["refID"]))
                    refNo = Convert.ToString(Request.QueryString["refID"]).Trim();
                lblLeaveRefNo.Text = refNo;
                SPSecurity.RunWithElevatedPrivileges(delegate() { UndertakingStatus(); });
            }

            #region  Button

            btnUpload.Click += new EventHandler(btnUpload_Click);
            btnSubmit.Click += new EventHandler(btnSubmit_Click);

            #endregion

        }


        private void UndertakingStatus()
        {
            try
            {
                lblMessage.Text = "";
                SPListItem oItems = null;
                SPQuery qry = new SPQuery();
                string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                qry.Query = camlQry;
                //qry.ViewFields = "<FieldRef Name='HandoverStatus' />";
                oItems = obj.GetSPListItem(SiteURL, SourceLstName, qry);
                if (oItems != null)
                {
                    ItemId = Convert.ToInt32(oItems["ID"]);
                    if (Convert.ToString(oItems["HandoverStatus"]) == "Yes")
                    {
                        if (!string.IsNullOrEmpty(Message))
                            lblMessage.Text = Message;
                        else
                            lblMessage.Text = "You already submitted the Handover form";
                        pnlAttAdd.Visible = false;
                        trAtt.Visible = true;
                        GetUndertakingData(); // Get Undertaking data from list
                        GetAttachment(); // Get attachments from Undertaking Attachment library
                    }
                    else
                    {
                        pnlAttAdd.Visible = true;
                        trAtt.Visible = false;
                        lblRecords.Text = "Attachments not found";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "UndertakingStatus";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


        }

        private void GetAttachment()
        {
            try
            {

                using (SPSite oSite = new SPSite(SiteURL))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        SPList oList = oWeb.Lists.TryGetList(MainLstName);
                        SPQuery qry = new SPQuery();
                        string camlQry = "<Where><Eq><FieldRef Name='Reference_x0020_Number' /><Value Type='Text'>" + Convert.ToString(refNo) + "</Value></Eq></Where>";
                        qry.Query = camlQry;
                        qry.ViewFields = "<FieldRef Name='File' />";
                        oWeb.AllowUnsafeUpdates = true;
                        SPListItemCollection oitm = oList.GetItems(qry);
                        gvAtts.DataSource = oitm.GetDataTable();
                        gvAtts.DataBind();
                        oWeb.AllowUnsafeUpdates = false;
                        if (gvAtts.Rows.Count > 0)
                        {
                            trAtt.Visible = true;
                            btnSubmit.Visible = false;
                        }
                        else
                        {
                            trAtt.Visible = false;
                            lblMessage.Text = "No Attachments found";
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "GetAttachment";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        private void GetUndertakingData()
        {
            string camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            SPListItem oItems = obj.GetSPListItem(SiteURL, MainListName, camlQry);
            if (oItems != null)
            {
                lblReferenceNo.Text = Convert.ToString(oItems["Reference_x0020_Number"]);
                dtDate.SelectedDate = Convert.ToDateTime(oItems["RequestDate"]);
            }
        }

        #region Upload File Add in List
        void btnUpload_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                lblMessage.Text = "";
                fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
                if (fileName != "")
                {
                    string _fileTime = DateTime.Now.ToFileTime().ToString();
                    string _fileorgPath = System.IO.Path.GetFullPath
                    (inputFile.PostedFile.FileName);
                    string _newfilePath = _fileTime + "~" + fileName;
                    length = (inputFile.PostedFile.InputStream.Length) / 1024;
                    string tempFolder = Environment.GetEnvironmentVariable("TEMP");
                    string _filepath = tempFolder + _newfilePath;
                    inputFile.PostedFile.SaveAs(_filepath);
                    AddRow(fileName, _filepath, length);
                    lblRecords.Visible = false;
                }
                else
                {
                    //lblRecords.Text = "Please select a File"; lblRecords.ForeColor = System.Drawing.Color.Red;
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Please select a File!');</script>"));
                    return;
                }
            });
        }

        #endregion

        #region RowDeleting

        protected void dgUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int recordToDelete = e.RowIndex;
            dt = (DataTable)Page.Session["Files"];
            int cn = dt.Rows.Count;
            dt.Rows.RemoveAt(recordToDelete);
            dt.AcceptChanges();
            Page.Session["Files"] = dt;
            dgUpload.DataSource = dt;
            dgUpload.DataBind();
            if (dt.Rows.Count == 0)
                lblRecords.Visible = true;
            else
                lblRecords.Visible = false;
        }

        #endregion


        #region File in SharePoint List

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                SPListItem item = null;

                dt = (DataTable)Page.Session["Files"];
                if (dt != null)
                {
                    if (dt.Rows.Count != 0)
                    {
                        string strDate = "";
                        string fileName = null;
                        String fileToUpload = "";

                        using (SPSite oSite = new SPSite(SiteURL))
                        {
                            using (SPWeb oWeb = oSite.OpenWeb())
                            {
                                strDate = System.DateTime.Now.Date.TimeOfDay.ToString();
                                SPFolder myLibrary = oWeb.Folders[MainLstName];
                                foreach (DataRow dr in dt.Rows)
                                {
                                    oWeb.AllowUnsafeUpdates = true;
                                    fileName = dr["Filename"].ToString();
                                    fileToUpload = dr["FilePath"].ToString();
                                    if (!System.IO.File.Exists(fileToUpload))
                                        throw new FileNotFoundException("File not found.", fileToUpload);
                                    // Prepare to upload
                                    Boolean replaceExistingFiles = true;
                                    FileStream fileStream = File.OpenRead(fileToUpload);

                                    string refNos = refNo.Replace("/", "_");

                                    fileName = refNos + " - " + fileName;
                                    // Upload document
                                    SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
                                    myLibrary.Update();
                                    // Commit 
                                    item = spfile.Item; ;
                                    item["FileDate"] = strDate;
                                    item["FileSize"] = Convert.ToDouble(dr["FileSize"]);
                                    item["Reference_x0020_Number"] = refNo;
                                    item.Update();
                                    fileStream.Close();
                                }

                                System.IO.File.Delete(fileToUpload);
                                dt = null;
                                Page.Session["Files"] = dt;
                                dgUpload.DataSource = dt;
                                dgUpload.DataBind();

                                Message = "Sucessfully Submited";

                                SetUndertakingStatus(oWeb);
                                oWeb.AllowUnsafeUpdates = false;
                                lblRecords.Visible = true;
                                UndertakingStatus();
                            }
                        }

                    }
                    else
                    {
                        pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Please select atleast one File!');</script>"));
                    }
                }
                else
                {
                    lblMessage.Text = "Stream Disposed";
                }

            });

        }

        #endregion



        /// <summary>
        /// Set undertaking status to Leave Request Form
        /// </summary>
        /// <param name="oWeb"></param>
        private void SetUndertakingStatus(SPWeb oWeb)
        {
            try
            {
                SPListItem oItem = oWeb.Lists.TryGetList(SourceLstName).GetItemById(ItemId);
                oItem["HandoverStatus"] = "Yes";
                AddUndertakingForm(oWeb, oItem);
                oItem.Update();
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "SetUndertakingStatus";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        /// <summary>
        /// Add Undertaking details to Form
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="oItemLeave"></param>
        private void AddUndertakingForm(SPWeb oWeb, SPListItem oItemLeave)
        {
            try
            {
                obj.AutoNoGeneration(MainListName, DocumentTypesList, lblReferenceNo, SiteURL);

                SPListItem oItemUT = oWeb.Lists.TryGetList(MainListName).Items.Add();
                oItemUT["Title"] = lblReferenceNo.Text;
                oItemUT["Reference_x0020_Number"] = lblReferenceNo.Text;
                oItemUT["RequestDate"] = dtDate.SelectedDate.Date;
                oItemUT["LeaveReferenceNo"] = lblLeaveRefNo.Text;
                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItemLeave["SubmittedFor"]));
                oItemUT["SubmittedFor"] = fldUser.User;
                oItemUT["EmployeeID"] = oItemLeave["EmployeeID"];
                oItemUT["Division"] = oItemLeave["Division"];
                oItemUT["Designation"] = oItemLeave["Designation"];
                oItemUT["Document_x0020_Status"] = "Approved";
                SPFieldUserValue UserName = null;
                //oWeb.EnsureUser(CurrentUser);
                SPUser User = oWeb.EnsureUser(CurrentUser); //oWeb.SiteUsers[CurrentUser];
                UserName = new SPFieldUserValue(oWeb, User.ID, User.Name);
                oItemUT["RequestedBy"] = UserName.User;
                oItemUT.Update();

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "AddUndertakingForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


        }

        #region AddMoreRows for file upload

        private void AddMoreColumns()
        {
            dt = new DataTable("Files");
            dc = new DataColumn("FileName", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("FilePath", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("FileSize", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dc = new DataColumn("KB", Type.GetType("System.String"));
            dt.Columns.Add(dc);
            dt.PrimaryKey = new DataColumn[] { dt.Columns["FileName"] };
            Page.Session["Files"] = dt;
        }
        #endregion

        #region AddRow for file upload

        private void AddRow(string file, string path, double length)
        {
            DataRow row = null;
            try
            {
                dt = (DataTable)Page.Session["Files"];
                if (dt == null)
                {
                    AddMoreColumns();
                }
                if (dt.Rows.Count > 0)
                {
                    row = dt.Rows.Find(file);
                }
                if (row == null)
                {
                    lblMessage.Visible = false;
                    dr = dt.NewRow();
                    dr["FileName"] = file;
                    dr["FilePath"] = path;
                    dr["FileSize"] = Convert.ToString(length);
                    dr["KB"] = "KB";
                    dt.Rows.Add(dr);
                    Page.Session["Files"] = dt;
                    dgUpload.DataSource = dt;
                    dgUpload.DataBind();//bind in grid
                }
                else
                {
                    //ScriptManager.RegisterClientScriptBlock(this, GetType(), "Duplication", "alert('Same file can not be uploaded');", true);
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Same file cannot be uploaded!');</script>"));
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "AddRow";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        #endregion


        protected void gvAtts_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    HyperLink lnkViewAttachments = e.Row.FindControl("lnkViewAttachments") as HyperLink;
                    lnkViewAttachments.NavigateUrl = SPContext.Current.Site.Url + "/sites/forms" + "/" + MainLstName + "/" + lnkViewAttachments.Text;
                    //e.Row.Cells[5].Text = GetAttachment(oitm);
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Undertaking Form" + " :: " + "Parent" + " :: " + "gvAtts_RowDataBound";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }




    }
}
